package com.wjy.consumer;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;

@SpringBootApplication
@EnableDiscoveryClient
public class ConsumerApplication {
    public static void main(String[] args) {
        SpringApplication.run(ConsumerApplication.class, args);
    }

    @Configuration
    public class RestTemplateConfiguration {
        @Bean
        public RestTemplate restTemplate() {
            return new RestTemplate();
        }
    }

    @RestController
    static class TestController {
        @Resource
        private DiscoveryClient discoveryClient;
        @Resource
        private RestTemplate restTemplate;
//        @Resource
//        private LoadBalancerClient loadBalancerClient;

        @GetMapping("/hello")
        public String hello(String name) {
            //1.获取服务<>的一个实例
            ServiceInstance serviceInstance;
            if (true) {
                //获取服务<>对应的实例列表
                List<ServiceInstance> instanceList = discoveryClient.getInstances("provider");
                //选择第一个
                serviceInstance = instanceList.size() > 0 ? instanceList.get(0) : null;
            } else {
//                serviceInstance = loadBalancerClient.choose("example");
            }
            //2.发起调用
            if (serviceInstance == null) {
                throw new IllegalStateException("获取不到实例.");
            }
            String targetUrl = serviceInstance.getUri() + "/echo?name=" + name;
            String response = restTemplate.getForObject(targetUrl, String.class);
            return "consumer:" + response;
        }
    }
}
